<template>
  <div class="login-page">
    <van-nav-bar
    class="loginTop"
  title="账号登录"
  left-arrow
  @click-left="onClickLeft"
/>
<van-form @submit="onSubmit">
  <van-field
    v-model="username"
    name="username"
    placeholder="请输入账号"
    :rules="[{ required: true, message: '请填写用户名' },{ pattern:/^\w{5,}$/ , message: '用户名至少包含5个字符' }]"
  />
  <van-field
    v-model="password"
    type="password"
    name="password"
    placeholder="请输入密码"
    :rules="[{ required: true, message: '请填写密码' },{ pattern:/^\w{6,}$/ , message: '密码至少包含6个字符' }]"
  />
  <div style="margin: 16px;">
    <van-button block type="info" native-type="submit">登录</van-button>
  </div>
</van-form>
<div class="go-register">
<router-link class="link" to="/register">还没有账号，去注册~</router-link>
  </div>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { setToken } from '@/utils/storage'
export default {
  name: 'login-page',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async  onSubmit (val) {
      // console.log('submit', val)
      const res = await login(val)
      // console.log(res)
      setToken(res.body.token)
      this.$toast.success('登录成功')
      this.$router.push('/')
    },
    onClickLeft () {
      this.$router.push('/users')
    }
  }
}
</script>

<style lang="less" scoped>
.link {
  color: #333;
  font-size: 14px;
}
.go-register {
  text-align: center;
}
.loginTop {
  background-color: #1cb676;
  margin-bottom: 20px;
}
</style>
